package com.rs.config;

import com.rs.entity.Student;
import com.rs.entity.login.User;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    /**
     * 拦截器方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("basePath",request.getContextPath());
        User user= (User) session.getAttribute("user");
        Student stu= (Student) session.getAttribute("stuuser");
        String requestURI = request.getRequestURI();
        //如果学生老师都未登录，跳转到学生登录
        if(user==null && stu==null){
            response.sendRedirect(request.getContextPath()+"/stu/login");
            return false;
        }
        //判断路径不是学生，如果老师session为空跳转到老师登录
        if(!requestURI.contains("/stu/")){
            if(user == null){
                response.sendRedirect(request.getContextPath()+"/login");
                return false;
            }
            //如果学生访问学生，学生session等于空
        }else if(requestURI.contains("/stu/")){
            if(stu==null){
                response.sendRedirect(request.getContextPath()+"/stu/login");
                return false;
            }
        }
        return true;
    }




    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
